package sharetime.playlist.service;

import java.util.List;

import org.springframework.stereotype.Service;

import sharetime.core.service.BaseManager;
import sharetime.playlist.domain.Playlist;
import sharetime.playlist.domain.PlaylistPermission;
import sharetime.user.domain.PermissionBase;
import sharetime.user.domain.User;

@Service("playlistPermissionManager")
public class DefaultPlaylistPermissionManager extends BaseManager implements
		IPlaylistPermissionManager {

	@Override
	public boolean hasPermission(long type, User user, Playlist playlist) {
		if (null == user) {
			return false;
		}

		String[] params = { "username" };
		Object[] values = { user.getUsername() };

		List<PermissionBase> permissions = dao
				.getInstancesByNamedQueryAndNamedParam(PermissionBase.class,
						"getPermissionsByUserName", params, values);

		for (PermissionBase p : permissions) {
			if (((PlaylistPermission) p).getPlaylist().getId() == playlist
					.getId()
					&& p.getBit(type)) {
				return true;
			}
		}

		return false;
	}

	@Override
	public void savePermission(PlaylistPermission permission) {
		dao.save(permission);
	}
}
